package edu.bu.trident.k9scheduler.server;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import edu.bu.trident.k9scheduler.client.GreetingService;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService {

	public String[] searchDogWalkers(String input) throws IllegalArgumentException {

		String[] dogWalkers = new String[2];
		
		String dogWalker1 = "Bucky's Paws N Pals &";
		dogWalker1 += "Have Pets? Love to travel?  Bucky's has the answer! ";
		dogWalker1 += "Bucky's is a unique pet care service offering Pet Nanny care. ";
		dogWalker1 += "Your pets will feel safe and secure having a pet care professional ";
		dogWalker1 += "staying with them while you are away.  We also offer daily care, ";
		dogWalker1 += "vacation care as well as long term care.  Thinking of taking a vacation? ";
		dogWalker1 += "Give us a call.  Once you've tried our unique service you'll never want to travel ";
		dogWalker1 += "with out us again. We've got alot of wagging tails that will agree.  We are currently ";
		dogWalker1 += "celebrating our 21st year in service and have enjoyed meeting every furry face along the way. ";
		dogWalker1 += "Call 617-416-1619 and schedule an appointment.";
		dogWalkers[0] = dogWalker1; 
		
		String dogWalker2 = "Hounds to Hooves, Etc &";
		dogWalker2 += "Let us provide that special care and attention for your pets while you are out of town or ";
		dogWalker2 += "during the day while you are at work. Our services include daily visits, walks and exercise ";
		dogWalker2 += "programs, non-professional grooming, barn services and overnight stays. We offer care for dogs ";
		dogWalker2 += "and cats, horses and barnyard critters, exotic birds, aquarium and marine life, small caged ";
		dogWalker2 += "pets, and special needs pets. We are licensed, insured and accredited! Our phone number is 617-416-1619";
		dogWalkers[1] = dogWalker2; 
	    
		return dogWalkers;
	}
 
	
	
	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid. 
		if (!isValidName(input)) {
			// If the input is not valid, throw an IllegalArgumentException back to
			// the client.
			throw new IllegalArgumentException(
					"Please enter valid user name and password");
		}

		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");

		// Escape data from the client to avoid cross-site script vulnerabilities.
		input = escapeHtml(input);
		userAgent = escapeHtml(userAgent);

		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + userAgent;
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
	
	private boolean isValidName(String name) {
		if (name == null || name.trim().length() < 1) {
			return false;
		}

		int index = name.indexOf(" ");
		String username = name.substring(0, index).trim();
		String password = name.substring(index).trim();

		Pattern p = null;
		Matcher m = null;

		// make sure there is only one '@' symbol
		int ndx_start = username.indexOf('@');
		int ndx_end = username.lastIndexOf('@');
		if (ndx_start == ndx_end && ndx_start != -1) {
			// break the string into local and domain
			String local = username.substring(0, ndx_start);
			String domain = username.substring(ndx_start + 1);

			// check local length is not greater than 64
			if (local.length() > 64)
				return false;

			// check domain length 255
			if (domain.length() > 255)
				return false;

			// finally check username string with the regex
			// source code help from:
			// http://java.sun.com/developer/technicalArticles/releases/1.4regex/
			p = Pattern.compile("^\\.|^\\@");
			m = p.matcher(username);
			if (m.find())
				return false;

			p = Pattern.compile("[^A-Za-z0-9\\.\\@_\\-~#]+");
			m = p.matcher(username);
			if (m.find())
				return false;
		}

		// Password must contain at least one of the following characters:
		// abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
		p = Pattern.compile("[A-Za-z]");
		m = p.matcher(password);
		if (!m.find())
			return false;

		// Password must contain at least one of the following digits:
		// 0123456789
		p = Pattern.compile("[0-9]");
		m = p.matcher(password);
		if (!m.find())
			return false;

		// Password must contain at least one of the following punctuation:
		// !"#$%&()''*+,-/:;<=>?_
		p = Pattern.compile("[!\"#$%&()''*+,-/:;<=>?_]");
		m = p.matcher(password);
		if (!m.find())
			return false;

		return true;
	}
}
